package dbms.absyn;

import java.util.List;

public class ConditionList {
	public int pos;
	public Condition condition;
	public ConditionList next;
	public boolean flag;
	public String relop;
	public int type = 0;
	
	//usual
	public ConditionList (int p, Condition c) {
		pos = p;
		flag = true;
		condition = c;
		type = 1;
		if (condition.type == 6) type = 4;
	}
	
	//NOT
	public ConditionList (int p, ConditionList cl) {
		pos = p;
		flag = false;
		next = cl;
		type = 2;
		if (condition.type == 6) type = 4;
	}
	
	//AND, OR
	public ConditionList (int p, Condition c, ConditionList cl, String s) {
		pos = p;
		flag = true;
		condition = c;
		next = cl;
		relop = s;
		type = 3;
		//if (condition.type == 6) type = 4;
	}

	public boolean satisfy(List<String> FieldList, List<Object> DataList) {
		String attrName;
		int index;
		Object v;
		switch(type) {
		case 1://usual
			
			attrName = condition.attr.attr.name;
			index = FieldList.indexOf(attrName);
			v = DataList.get(index);
			
			return condition.satisfy(v);
			
		case 2://NOT
			
			return (!next.satisfy(FieldList, DataList));
			
		case 3://AND OR
			
			if (condition.type == 6) {
				String attrNameA = condition.attr1.attr.name;
				String attrNameB = condition.attr2.attr.name;
				int indexA = FieldList.indexOf(attrNameA);
				int indexB = FieldList.indexOf(attrNameB);
				Object va = DataList.get(indexA);
				Object vb = DataList.get(indexB);
				//AND
				if (relop.equals("AND")) {
					if (!condition.satisfyAttr(va, vb)) return false;
					else {
						return next.satisfy(FieldList, DataList);
					}
				}
				//OR
				if (relop.equals("OR")) {
					if (condition.satisfyAttr(va, vb)) return true;
					else {
						return next.satisfy(FieldList, DataList);
					}
				}
			}
			else {
				attrName = condition.attr.attr.name;
				index = FieldList.indexOf(attrName);
				v = DataList.get(index);
				//AND
				if (relop.equals("AND")) {
					if (!condition.satisfy(v)) return false;
					else {
						return next.satisfy(FieldList, DataList);
					}
				}
				//OR
				if (relop.equals("OR")) {
					if (condition.satisfy(v)) return true;
					else {
						return next.satisfy(FieldList, DataList);
					}
				}
			}
			
		case 4://special case
			
			String attrNameA = condition.attr1.attr.name;
			String attrNameB = condition.attr2.attr.name;
			int indexA = FieldList.indexOf(attrNameA);
			int indexB = FieldList.indexOf(attrNameB);
			Object va = DataList.get(indexA);
			Object vb = DataList.get(indexB);
			return condition.satisfyAttr(va, vb);
		}
		//Unexpected Case
		return false;
	}
}